import inspect
# https://www.osgeo.cn/tornado/util.html#tornado.util.import_object
from tornado.util import import_object
from tornado.web import url

from core.utils.module_utils import get_all_modules


class HandlerDecorate:
    """路由装饰器
    1. 实质上路由装饰器只是给装饰的类添加了__url_path__的属性
    2. 我们初始化的时候就通过__url_path__这个属性来判断当前的类是路由的处理器
    3. __url_path_index__用来给路由进行排序
    """

    def __init__(self, path, index=None) -> None:
        self.__url_path__ = path
        self.__url_path_index__ = index

    def __call__(self, cls):
        cls.__url_path__ = self.__url_path__
        cls.__url_path_index__ = self.__url_path_index__

        return cls


class OpenHandler:
    """路由容器
    1. 初始化的时候获取路由的容器类和工具类
    2. 返回tornado路由列表
    """

    def __init__(self, source_libs) -> None:
        self.source_libs = source_libs   # 传递目录名，用于获取目录下所有使用装饰器的类
        self.handler_libs = []  # 存储路由的容器

    def get_handlers(self):
        self._handler_libs_ = []
        _modules = []  # 目录下所有的moudule容器
        for _path in self.source_libs:
            _modules += get_all_modules(_path, "handler")

        for _module in _modules:
            self.handler_libs += [
                dict(
                    path=_member.__url_path__,
                    handler=f"{_member.__module__}.{_member.__name__}"
                )
                for _name,_member in inspect.getmembers(_module, inspect.isclass)
                if hasattr(_member, "__url_path__")
            ]

        # 排序
        # self.handler_libs.sort(key=lambda x: x['index'])

        # 生成tornado的路由对象
        _result = []
        for _handler_lib in self.handler_libs:
            # 遍历生成tornado的路由对象
            _path = _handler_lib.get("path")
            _result.append(
                url(_path, import_object(_handler_lib.get("handler"))))

        # 所有的路由列表
        return _result
